package phone.qyg.com.qyg.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PopuPdfData;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.TransformController;
import com.artifex.mupdfdemo.MuPDFActivity;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.MessageFormat;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.CultureDetail;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2018/1/8 15:28
 * 邮箱：lanbuhan@163.com
 * 功能：文化超市-文档详情
 */
@ContentView(R.layout.culture_file_detail)
public class CultureFileDetailActivity extends BaseActivity {

    String FILE_SIZE = "文件大小：<font color='#ffa200'>{0}</font>";
    String FILE_PAGE = "页数：<font color='#ffa200'>{0}</font>页";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.title)
    TextView title;

    @ViewInject(R.id.time)
    TextView time;

    @ViewInject(R.id.code)
    TextView code;

    @ViewInject(R.id.author)
    TextView author;

    @ViewInject(R.id.type)
    TextView type;

    @ViewInject(R.id.publish)
    TextView publish;

    @ViewInject(R.id.keyword)
    TextView keyword;

    @ViewInject(R.id.content)
    TextView content;

    @ViewInject(R.id.file_size)
    TextView file_size;

    @ViewInject(R.id.file_page)
    TextView file_page;

    @ViewInject(R.id.item_img)
    ImageView item_img;

    @ViewInject(R.id.look_file)
    RelativeLayout look_file;

    @ViewInject(R.id.file_layout)
    LinearLayout file_layout;

    PopupWindow pupoClassifyCourse;

    ShareAction mShareAction;

    CultureDetail model;

    int resId;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();

        if(obj instanceof Base){
            Base model = (Base) obj;
            resId = model.id;
        }else if(obj instanceof CollectionItem){
            CollectionItem item = (CollectionItem) obj;
            resId = item.objectId;
        }

    }

    @Override
    public void initData(Bundle savedInstanceState) {

        mapKeys.put(AppHttpKey.CULTURE_RES_ID,String.valueOf(resId));

        AppHttpRequest.httpRequestDefalut(ApplicationConfig.RES_INFO_DETAIL,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, CultureDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }else{
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });
    }


    private void setData(){
        if(null == model) return;

        back.setText(model.title);
        title.setText(model.title);
        time.setText(addStr(R.string.appear_time,model.pubTime));
        code.setText(addStr(R.string.res_code,model.code));
        author.setText(addStr(R.string.author,model.author));
        type.setText(addStr(R.string.type,model.resClassName));
        publish.setText(addStr(R.string.publishing_unit,model.publishUnit));
        keyword.setText(addStr(R.string.keyword,model.keywords));
        content.setText(setAttributeText(model.content));

        CommonUtil.setTextViewDrawableDirection(chollect,4,
                (model.isCollection == 0)?
                        R.drawable.title_collect_normal:
                        R.drawable.title_collect_select);

        setImgPath(model.fixImgUrl,item_img, OptionImageUtils.getRectRatio43());

        if(model.hasFile == 1){
            file_layout.setVisibility(View.GONE);
            return;
        }
        CommonUtil.textViewSetText(file_size,MessageFormat.format(FILE_SIZE,model.fileSize).toString());
        CommonUtil.textViewSetText(file_page,MessageFormat.format(FILE_PAGE,String.valueOf(model.filepage)).toString());



    }

    @Event(value = {R.id.back,R.id.chollect,R.id.share,R.id.look_file})
    private void viewOnClick(View v){
        if(model == null && (v != back)){
            return;
        }
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.chollect:
            if(isUserLogin()){
                final int isCollection = model.isCollection;
                AppHttpRequest.collection(model.id, isCollection, "3", model.title, new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            PromptManager.showToast((isCollection == 0)?R.string.conllection_sucess:R.string.conllection_quit_sucess);
                            model.isCollection = (isCollection == 0) ? 1:0;
                            CommonUtil.setTextViewDrawableDirection(chollect,4,(model.isCollection == 0)? R.drawable.title_collect_normal: R.drawable.title_collect_select);
                        }
                    }
                });
            }else{
                TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
            }
            break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(this,
                        model.shareAddress,
                        model.title,
                        model.content,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.look_file:
                //阅读
                String filePath = model.filePath;

                /**
                 *
                 || filePath.endsWith(".xls") || filePath.endsWith(".xlsx")
                 || filePath.endsWith(".ppt") || filePath.endsWith(".pptx"))
                 */
                //文件地址
                if(filePath.endsWith(".docx") ||(filePath.endsWith(".doc"))){
//                    StringBuffer buffer = new StringBuffer(ApplicationConfig.APP_OFFICE_HTMl);
//                    buffer.append(filePath);
//                    Uri uri = Uri.parse(buffer.toString());
//                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
//                    startActivity(intent);
                    Base base = new Base(filePath,model.title);
                    TransformController.transformControllerModel(QXApplication.getContext(),WordActivity.class,base);
                }else if(filePath.endsWith(".pdf")){
                    pupoClassifyCourse = PopuPdfData.setPupoClassifyCourse(back, filePath, new PopuPdfData.OnPdfState() {
                        @Override
                        public void state(PDFSTATE state, final String url, PopupWindow popupWindow) {

                            if(state.equals(PDFSTATE.SUCESS)){
                                CommonUtil.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(pupoClassifyCourse != null && pupoClassifyCourse.isShowing()){
                                            pupoClassifyCourse.dismiss();
                                            pupoClassifyCourse = null;
                                        }
                                        Uri uri = Uri.parse("content://"+url);
                                        Intent intent = new Intent(QXApplication.getContext(), MuPDFActivity.class);
                                        intent.setAction(Intent.ACTION_VIEW);
                                        intent.setData(uri);
                                        QXApplication.getContext().startActivity(intent);
                                    }
                                });
                            }

                        }
                    });
                }else if(filePath.endsWith(".jpg") || filePath.endsWith(".png")){
//                    Uri uri = Uri.parse(filePath.toString());
//                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
//                    startActivity(intent);
                    Base base = new Base(filePath.toString(),model.title);
                    TransformController.transformControllerModel(QXApplication.getContext(),CultureFileImgLookActivity.class,base);
                }else if(filePath.endsWith("txt")){
                    Base base = new Base(filePath.toString(),model.title);
                    TransformController.transformControllerModel(QXApplication.getContext(),CultureFileTxtActivity.class,base);
                }else{
                    PromptManager.showToast(R.string.culture_file_pc_look);
                }
                break;
        }
    }


    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }

    @Override
    public void initViewHandler() {}


}
